package com.graduation_design.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation_design.entity.AppCartItem;
import com.graduation_design.entity.AppProduct;
import com.graduation_design.entity.AppSkuStock;
import com.graduation_design.service.AppCartItemService;
import com.graduation_design.mapper.AppCartItemMapper;
import com.graduation_design.service.AppProductService;
import com.graduation_design.service.AppSkuStockService;
import com.graduation_design.service.AppUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
* @author 从南
* @description 针对表【app_cart_item】的数据库操作Service实现
* @createDate 2024-02-16 18:15:58
*/
@Service
public class AppCartItemServiceImpl extends ServiceImpl<AppCartItemMapper, AppCartItem>
    implements AppCartItemService{

    @Resource
    AppUserService appUserService;

    @Resource
    AppCartItemMapper appCartItemMapper;

    @Resource
    AppSkuStockService appSkuStockService;

    @Resource
    AppProductService appProductService;

    /**
     * 获取当前用户的购物车列表
     */
    @Override
    public List<AppCartItem> getCurrent() {
        Long userId = appUserService.getCurrentUserId();
        return appCartItemMapper.getCartItemsWithProductInfo(new QueryWrapper<AppCartItem>()
                .eq("user_id", userId)
                .orderByDesc("created"));
    }

    /**
     * 购物车数量
     */
    @Override
    public long getCount() {
        Long userId = appUserService.getCurrentUserId();
        return this.count(new QueryWrapper<AppCartItem>().eq("user_id", userId));
    }

    /**
     * 购物车总金额
     */
    @Override
    public Object getTotal(ArrayList<Long> ids) {

        long userId = appUserService.getCurrentUserId();

        // 获取选中的购物车
        List<AppCartItem> cartItems = new ArrayList<>();
        if (!ids.isEmpty()) {
            cartItems = appCartItemMapper.getCartItemsWithProductInfo(new QueryWrapper<AppCartItem>()
                    .eq("user_id", userId)
                    .in("c.id", ids)
                    .orderByDesc("created")
            );
        }

        // 计算总金额，价格、数量
        BigDecimal total = cartItems.stream()
                .map(item -> item.getPrice().multiply(new BigDecimal(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        // 优惠，满减数据等

        return MapUtil.of("total", total);
    }

    /**
     * 修改商品数量
     */
    @Override
    public void updateQuantity(Long cartItemId, Integer quantity) {

        AppCartItem cartItem = this.getById(cartItemId);
        // 库存判断
        AppSkuStock skuStock = appSkuStockService.getSku(cartItem.getSkuId(), cartItem.getProductId());
        Assert.isTrue(skuStock.getStock() >= quantity, "库存不足");

        // 更新购买数量
        this.update(new UpdateWrapper<AppCartItem>()
                .eq("id", cartItemId)
                .eq("user_id", appUserService.getCurrentUserId())
                .set("quantity", quantity)
                .set("updated", LocalDateTime.now())
        );
    }

    /**
     * 加入购物车
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(AppCartItem appCartItem) {

        appCartItem.setUserId(appUserService.getCurrentUserId());

        // 判断商品是否为空、是否上架
        AppProduct appProduct = appProductService.getById(appCartItem.getProductId());
        Assert.isTrue(appProduct != null && appProduct.getIsOnSale(), "该商品已下架");

        // 判断库存是否足够
        AppSkuStock skuStock = appSkuStockService.getSku(appCartItem.getSkuId(), appCartItem.getProductId());
        Assert.isTrue(skuStock.getStock() >= appCartItem.getQuantity(), "库存不足");

        // 判断之前是否已经存在了该商品购物车
        AppCartItem exitItem = this.getOne(new QueryWrapper<AppCartItem>()
                .eq("user_id", appCartItem.getUserId())
                .eq("product_id", appCartItem.getProductId())
                .eq("sku_id", appCartItem.getSkuId())
        );

        // 购买数量
//        int quantity = exitItem == null ? appCartItem.getQuantity() : appCartItem.getQuantity() + exitItem.getQuantity();

        // 当购物车中本来就存在这种规格的商品了，那么只需要在原来的额基础上增加数量即可
        // 购物车中没有该规格商品，那么就需要添加一条记录
        if (exitItem == null) {
            appCartItem.setCreated(LocalDateTime.now());
            appCartItem.setUserId(appCartItem.getUserId());
            this.save(appCartItem);
        } else {
            // 购物车中存在该商品
            exitItem.setUpdated(LocalDateTime.now());
            // 原来数量加上新购买数量
            exitItem.setQuantity(exitItem.getQuantity() + appCartItem.getQuantity());
            this.updateById(exitItem);
        }
    }

    /**
     * 立即购买的购物车
     */
    @Override
    public AppCartItem getCombinedCartItems(long userId, Long productId, Long skuId, Integer quantity) {

        AppProduct product = appProductService.getById(productId);

        Assert.notNull(product, "商品已下架");

        AppCartItem item = new AppCartItem();

        item.setProductId(productId);
        item.setSkuId(skuId);
        item.setQuantity(quantity);

        item.setProductName(product.getName());
        item.setProductImage(product.getImage());
        item.setProductSn(product.getSn());
        item.setCategoryId(product.getCategoryId());

        item.setUserId(userId);

        if (skuId == -1) {
            item.setSkuId(skuId);
            item.setSku("默认规格");
            item.setPrice(product.getPrice());
        } else {
            AppSkuStock skuStock = appSkuStockService.getById(skuId);
            item.setSkuId(skuId);
            item.setSku(skuStock.getSku());
            item.setPrice(skuStock.getPrice());
        }
        return item;
    }
}




